/* ***** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/LGPL 2.1/GPL 2.0

The contents of this file are subject to the Mozilla Public License Version 
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ 
Software distributed under the License is distributed on an "AS IS" basis, 
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is the Ironsoft Kumquat.

The Initial Developer of the Original Code is
Ironsoft.
Portions created by the Initial Developer are Copyright (C) 2011
the Initial Developer. All Rights Reserved.

Contributor(s):
  Tomas de Priede <tdepriede@ironsoft.com.ar>

Alternatively, the contents of this file may be used under the terms of
either of the GNU General Public License Version 2 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead 
of those above. If you wish to allow use of your version of this file only 
under the terms of either the GPL or the LGPL, and not to allow others to 
use your version of this file under the terms of the MPL, indicate your 
decision by deleting the provisions above and replace them with the notice 
and other provisions required by the GPL or the LGPL. If you do not delete 
the provisions above, a recipient may use your version of this file under
 the terms of any one of the MPL, the GPL or the LGPL

 ***** END LICENSE BLOCK *****
 */

/**
 * File name: AppController.java
 *
 * Project name: Kumquat
 *
 * Created at: 12/10/2011
 *
 * Author: Tomiito
 */
package ar.com.ironsoft.kumquat.client;

import ar.com.ironsoft.kumquat.client.events.AccountViewEvent;
import ar.com.ironsoft.kumquat.client.events.AccountViewEventHandler;
import ar.com.ironsoft.kumquat.client.events.ActualBudgetViewEvent;
import ar.com.ironsoft.kumquat.client.events.ActualBudgetViewEventHandler;
import ar.com.ironsoft.kumquat.client.events.GoHomeEvent;
import ar.com.ironsoft.kumquat.client.events.GoHomeEventHandler;
import ar.com.ironsoft.kumquat.client.events.LoginEvent;
import ar.com.ironsoft.kumquat.client.events.LoginEventHandler;
import ar.com.ironsoft.kumquat.client.events.PasswordChangeViewEvent;
import ar.com.ironsoft.kumquat.client.events.PasswordChangeViewEventHandler;
import ar.com.ironsoft.kumquat.client.presenter.AccountPresenter;
import ar.com.ironsoft.kumquat.client.presenter.ActualBudgetPresenter;
import ar.com.ironsoft.kumquat.client.presenter.LoginPresenter;
import ar.com.ironsoft.kumquat.client.presenter.MainPresenter;
import ar.com.ironsoft.kumquat.client.presenter.PasswordChangePresenter;
import ar.com.ironsoft.kumquat.client.presenter.Presenter;
import ar.com.ironsoft.kumquat.client.services.LoginService;
import ar.com.ironsoft.kumquat.client.services.LoginServiceAsync;
import ar.com.ironsoft.kumquat.client.view.LoginView;
import ar.com.ironsoft.kumquat.client.view.MainView;
import ar.com.ironsoft.kumquat.shared.dto.UserAccountDTO;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author Tomiito
 * 
 */
public class AppController implements ValueChangeHandler<String> {

	LoginServiceAsync loginService = (LoginServiceAsync) GWT.create(LoginService.class);

	private final SimpleEventBus eventBus;
	private MainPresenter mainPresenter;
	private LoginPresenter loginPresenter;
	private AccountPresenter accountPresenter;
	private ActualBudgetPresenter actualBudgetPresenter;
	private PasswordChangePresenter passwordChangePresenter;

	public AppController(SimpleEventBus eventBus) {
		this.eventBus = eventBus;
		bind();
	}

	private void bind() {
		History.addValueChangeHandler(this);

		eventBus.addHandler(LoginEvent.TYPE, new LoginEventHandler() {
			@Override
			public void onLogin(LoginEvent event) {
				initMainView(event.getUser());
			}
		});

		eventBus.addHandler(GoHomeEvent.TYPE, new GoHomeEventHandler() {
			@Override
			public void onGoHome(GoHomeEvent event) {
				reinitMainView();
			}
		});

		eventBus.addHandler(ActualBudgetViewEvent.TYPE, new ActualBudgetViewEventHandler() {

			@Override
			public void onViewActualBudget(ActualBudgetViewEvent event) {
				doViewActualBudget();
			}
		});

		eventBus.addHandler(AccountViewEvent.TYPE, new AccountViewEventHandler() {

			@Override
			public void onAccountView(AccountViewEvent event) {
				doViewAccount();
			}
		});

		eventBus.addHandler(PasswordChangeViewEvent.TYPE, new PasswordChangeViewEventHandler() {

			@Override
			public void onPasswordChangeView(PasswordChangeViewEvent event) {
				doViewPasswordChange();
			}
		});

	}

	public void go() {
		loginService.getLoggedInUser(new AsyncCallback<UserAccountDTO>() {

			@Override
			public void onSuccess(UserAccountDTO result) {
				if (result == null)
					doLogin();
				else
					initMainView(result);

			}

			@Override
			public void onFailure(Throwable caught) {
				GWT.log("Error on getting value from session");
				Window.alert("The application is not working well. Please refresh your browser");

			}
		});

	}

	public void doLogin() {
		GWT.log("AppController: Creating Login Page");
		loginPresenter = getLoginPresenter();
		loginPresenter.go(Kumquat.get().getMainPanel());
		History.newItem("login");
	}

	public void doLogout() {
		loginService.logout(new AsyncCallback<Void>() {
			@Override
			public void onSuccess(Void result) {
				GWT.log("AppController: Logged out");
				Kumquat.get().root.clear();
				mainPresenter = null;
				doLogin();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("The logout action fails. Please try again before close your browser");
			}
		});

	}

	public void reinitMainView() {
		History.newItem("main");
	}

	public void doViewActualBudget() {
		History.newItem("actualBudget");
	}

	public void doViewAccount() {
		History.newItem("editAccount");
	}

	public void doViewPasswordChange() {
		History.newItem("passwordChange");
	}

	public void initMainView(UserAccountDTO userAccount) {
		GWT.log("AppController: Creating MainPresenter");
		mainPresenter = new MainPresenter(userAccount, eventBus, new MainView());
		mainPresenter.go(Kumquat.get().getMainPanel());
		History.newItem("main");
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();

		if (token != null) {
			Presenter presenter = null;

			if (token.equals("main")) {
				presenter = mainPresenter;
				presenter.go(Kumquat.get().getMainPanel());
				return;
			} else if (token.equals("login")) {
				presenter = getLoginPresenter();
				presenter.go(Kumquat.get().getMainPanel());
				return;
			} else if (token.equals("editAccount")) {
				presenter = getAccountPresenter();
				presenter.go(mainPresenter.getMainDisplay().getMainContentPanel());
				return;
			} else if (token.equals("actualBudget")) {
				presenter = getActualBudgetPresenter();
				presenter.go(mainPresenter.getMainDisplay().getMainContentPanel());
				return;
			} else if (token.equals("passwordChange")) {
				presenter = getPasswordChangePresenter();
				presenter.go(mainPresenter.getMainDisplay().getMainContentPanel());
				return;
			} else if (token.equals("logout")) {
				doLogout();
				return;
			}

		}

	}

	private PasswordChangePresenter getPasswordChangePresenter() {
		if (passwordChangePresenter == null)
			passwordChangePresenter = new PasswordChangePresenter(eventBus, mainPresenter);
		return passwordChangePresenter;
	}

	private ActualBudgetPresenter getActualBudgetPresenter() {
		if (actualBudgetPresenter == null)
			actualBudgetPresenter = new ActualBudgetPresenter(eventBus, mainPresenter);
		return actualBudgetPresenter;
	}

	private AccountPresenter getAccountPresenter() {
		if (accountPresenter == null)
			accountPresenter = new AccountPresenter(eventBus, mainPresenter);
		return accountPresenter;
	}

	private LoginPresenter getLoginPresenter() {
		if (loginPresenter == null)
			loginPresenter = new LoginPresenter(loginService, eventBus, new LoginView());
		return loginPresenter;
	}

}
